package com.nercel.dsj.gksales.util;

import com.nercel.dsj.gksales.constant.Const;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.time.DateUtils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @author sunlin
 * @date 2018-12-7
 */
public class JwtUtil{

	/**
	 * 由字符串生成加密key
	 * @return
	 */
	public static SecretKey generalKey() {
		String stringKey = Const.JWT_SECRET;
		byte[] encodedKey = Base64.decodeBase64(stringKey);
		SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
		return key;
	}

	/**
	 * 创建jwt
	 * @param subject
	 * @param ttlSeconds
	 * @return
	 * @throws Exception
	 */
	public static String createJWT(String subject, int ttlSeconds) throws Exception {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		Date now = new Date();
		SecretKey key = generalKey();
		return Jwts.builder()
			.setSubject(subject)
			.signWith(signatureAlgorithm, key)
			.setExpiration(DateUtils.addSeconds(now, ttlSeconds))
			.compact();
	}

	/**
	 * 解密jwt
	 * @param jwt
	 * @return
	 * @throws Exception
	 */
	public static Claims parseJWT(String jwt) throws Exception{
		SecretKey key = generalKey();
		Claims claims = Jwts.parser()
				.setSigningKey(key)
				.parseClaimsJws(jwt).getBody();
		return claims;
	}
//
//	/**
//	 * 生成subject信息
//	 * @param user
//	 * @return
//	 */
//	public static String generalSubject(t_user user){
//		JSONObject jo = new JSONObject();
//		jo.put("userId", user.getId());
//		jo.put("mobile", user.getMobile());
//		return jo.toJSONString();
//	}

}
